<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="70px"
    >
      <el-form-item label="部门" prop="deptId">
        <div style="width: 200px">
          <treeselect
            class="treeselect-main"
            v-model="queryParams.deptId"
            :options="deptOptions"
            :normalizer="normalizerSearch"
            :show-count="true"
            placeholder="请选择部门"
          />
        </div>
      </el-form-item>
      <el-form-item label="设备" prop="equipmentId">
        <el-select
          v-model="queryParams.equipmentId"
          placeholder="请选择设备"
          clearable
          size="small"
        >
          <el-option
            v-for="item in equipmentOptions"
            :key="item.equipmentId"
            :label="item.equipmentName"
            :value="item.equipmentId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="workingName">
        <el-date-picker
          v-model="queryParams.time"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          align="right"
          size="small"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '00:00:00']"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="任务名称" prop="workingName">
        <el-input
          v-model="queryParams.workingName"
          placeholder="请输入任务名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['technology:working:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['technology:working:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-warning-outline"
          size="mini"
          @click="handleForceEdit"
          v-if="forceEdit"
          v-hasPermi="['technology:working:forceEdit']"
          >强制修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['technology:working:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5" v-if="yjswShow">
        <el-button
          type="primary"
          icon="el-icon-video-play"
          size="mini"
          :disabled="single"
          @click="handleStart"
          v-hasPermi="['technology:working:start']"
          >开始任务</el-button
        >
      </el-col>
      <el-col :span="1.5" v-if="yjswShow">
        <el-button
          type="primary"
          icon="el-icon-video-pause"
          size="mini"
          :disabled="single"
          @click="handleSuspend"
          v-hasPermi="['technology:working:suspend']"
          >暂停任务</el-button
        >
      </el-col>
      <el-col :span="1.5" v-if="yjswShow">
        <el-button
          type="primary"
          icon="el-icon-refresh"
          size="mini"
          :disabled="single"
          @click="handleContinue"
          v-hasPermi="['technology:working:continueWorking']"
          >继续任务</el-button
        >
      </el-col>
      <el-col :span="1.5" v-if="yjswShow">
        <el-button
          type="primary"
          icon="el-icon-success"
          size="mini"
          :disabled="single"
          @click="handleFinish"
          v-hasPermi="['technology:working:finish']"
          >结束任务</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-download"
          size="mini"
          :loading="btnLoading"
          @click="handleExport"
          v-hasPermi="['technology:working:export']"
          >导出</el-button
        >
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="9">
        <el-table
          :cell-style="{ padding: this.tablePadding }"
          v-loading="loading"
          :data="workingList"
          @selection-change="handleSelectionChange"
          highlight-current-row
          @row-click="rowClick"
          :row-key="getRowKeys"
          :height="height"
          ref="interfaceTable"
        >
          <el-table-column type="selection" width="55" align="center" :reserve-selection="true"/>
          <!-- <el-table-column label="任务ID" align="center" prop="workingId" /> -->
          <el-table-column label="任务名称" align="center" prop="workingName" />
          <el-table-column
            label="任务状态"
            align="center"
            prop="status"
            :formatter="statusFormat"
          />
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          small
          layout="prev, pager, next"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
      <el-col :span="15"
        ><el-card class="box-card" style="font-size: 14px">
          <div slot="header" class="clearfix">
            <span
              >{{ details.workingName
              }}<span>
                <el-tag
                  v-show="workingList.length > 0"
                  style="margin-left: 15px"
                  :type="getColor(details.status)"
                  >{{ statusFormat(details) }}</el-tag
                ></span
              ></span
            >
            <!-- <el-button style="float: right; padding: 3px 0" type="text"
              ></el-button
            > -->
          </div>
          <div class="display-flex flex-wrap">
            <div class="item-width">编号：{{ details.workingId }}</div>
            <div class="item-width">部门：{{ details.deptName }}</div>
            <div class="item-width">设备：{{ details.equipmentName }}</div>
            <div class="item-width">
              增材方式：{{ details.technologyMaterialAddMethodName }}
            </div>
            <div class="item-width">创建时间：{{ details.createTime }}</div>
            <div class="item-width">开始时间：{{ details.startTime }}</div>
            <div class="item-width">结束时间：{{ details.endTime }}</div>
            <el-tooltip
              :disabled="String(details.description).length < 5"
              :content="String(details.description)"
              placement="top"
            >
              <div class="item-width max-text">
                任务描述：{{ details.description }}
              </div>
            </el-tooltip>
            <el-tooltip
              :disabled="String(details.remark).length < 5"
              :content="String(details.remark)"
              placement="top"
            >
              <div class="item-width max-text">备注：{{ details.remark }}</div>
            </el-tooltip>
          </div>
        </el-card>
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <el-tabs v-model="activeName">
              <el-tab-pane label="采集数据" name="second">
                <data-tab :id="workingId" :equipmentId="equipmentId" />
              </el-tab-pane>
              <el-tab-pane label="任务附件" name="five">
                <file-tab :id="workingId" :status="details.status" />
              </el-tab-pane>
            </el-tabs>
          </div> </el-card
      ></el-col>
    </el-row>

    <!-- 添加或修改工艺管理加工任务 对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form
        ref="form"
        :inline="true"
        layout="inline"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="任务名称" prop="workingName">
          <div class="input-width">
            <el-input
              size="small"
              v-model="form.workingName"
              placeholder="请输入任务名称"
            />
          </div>
        </el-form-item>
        <el-form-item label="选择设备" prop="equipmentId">
          <div class="input-width">
            <el-select
              v-model="form.equipmentId"
              placeholder="请选择设备"
              clearable
              size="small"
            >
              <el-option
                v-for="item in equipmentOptions"
                :key="item.equipmentId"
                :label="item.equipmentName"
                :value="item.equipmentId"
                :disabled="item.status == 0"
              ></el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="部门" prop="deptId">
          <div style="width: 210px">
            <treeselect
              class="treeselect-main"
              v-model="form.deptId"
              :options="deptOptions"
              :normalizer="normalizer"
              :show-count="true"
              placeholder="请选择归属部门"
            />
          </div>
        </el-form-item>
        <el-form-item label="任务描述" prop="description">
          <div class="input-width">
            <el-input
              size="small"
              v-model="form.description"
              placeholder="请输入任务描述"
            />
          </div>
        </el-form-item>

        <el-form-item label="增材方式" prop="technologyMaterialAddMethodId">
          <div class="input-width">
            <el-select
              size="small"
              v-model="form.technologyMaterialAddMethodId"
              placeholder="请选择增材方式"
              clearable
            >
              <el-option
                v-for="dict in materialAddMethodOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="parseInt(dict.dictValue)"
                :disabled="dict.status == 1"
              >
                <span style="float: left">{{ dict.dictDataAbbreviation }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{
                  dict.dictLabel
                }}</span>
              </el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="平均电价" prop="electricityPrice" v-if="yjswShow">
          <div class="input-width">
            <el-input
              size="small"
              v-model="form.electricityPrice"
              placeholder="请输入平均电价"
            />
          </div>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <div class="input-width">
            <el-input
              type="textarea"
              v-model="form.remark"
              placeholder="请输入备注"
            />
          </div>
        </el-form-item>
        <model-material ref="materialRef" :setSelectItem="setSelectItems" />
        <div style="margin-top: 10px" v-if="yjswShow">
          <process-parameters
            ref="parametersRef"
            :id="form.equipmentId"
            :selectItems="selectItems"
          />
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          :loading="btnLoading"
          v-funThrottle="[submitForm]"
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listWorking,
  getWorking,
  delWorking,
  addWorking,
  updateWorking,
  startWorking,
  suspendWorking,
  continueWorking,
  finishWorking,
  forceEditWorking
} from "@/api/technology/working";
import { listDept } from "@/api/system/dept";
import { listInfo } from "@/api/equipment/info";
import DataTab from "./components/DataTab.vue";
import FileTab from "./components/FileTab.vue";
import ModelMaterial from "./components/ModelMaterial.vue";
// import ProcessParameters from "./components/ProcessParameters.vue";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "Working",
  components: {
    FileTab,
    ModelMaterial,
    DataTab,
    Treeselect,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      forceEdit: false, //强制修改
      // 选中数组
      ids: [],
      workingNames: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工艺管理加工任务 表格数据
      workingList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 任务状态字典
      statusOptions: [],
      activeName: "five",
      workingId: "", //初始化首个详情ID
      equipmentId: "",
      tableCheckbox:[],
      height: document.documentElement.scrollHeight - 300 + "px",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        time: [],
        workingCategoryId: null,
        workingName: null,
        equipmentId: null,
        deptId: null,
        status: null,
        technologyMaterialAddMethodId: null,
      },
      equipmentOptions: [],
      selectItems: [], //工艺预设
      setSelectItems: [], //材料
      // 公司选项
      deptOptions: [],

      materialAddMethodOptions: [],
      technologyMaterialAddMethodIds: null,
      // 表单参数
      form: {},
      btnLoading: false,
      details: {}, //右侧详情对象
      // 表单校验
      rules: {
        workingNumber: [
          { required: true, message: "任务编码不能为空", trigger: "blur" },
        ],
        workingName: [
          { required: true, message: "任务名称不能为空", trigger: "blur" },
        ],
        equipmentId: [
          { required: true, message: "设备ID不能为空", trigger: "blur" },
        ],
        deptId: [
          { required: true, message: "公司ID不能为空", trigger: "blur" },
        ],
        description: [
          { required: true, message: "任务描述不能为空", trigger: "blur" },
        ],
        status: [
          { required: true, message: "任务状态不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getDeptOptions();
    this.getMaterialAddMethodOptions();
    this.getEquipmentOptions();
    this.getDicts("technology_work_status").then((response) => {
      this.statusOptions = response.data;
    });
  },
  watch: {
    $route: {
      handler: function (route) {
        if (route.query.equipmentId) {
          this.queryParams.equipmentId = parseInt(route.query.equipmentId);
          this.getList();
        }
      },
      immediate: true,
    },
  },
  methods: {
    getRowKeys(row) {
      return row.workingId;
    },
    // 强制修改
    handleForceEdit(row){
     this.handleUpdate(row)
      this.isForceEdit=true
    },
    getColor(status) {
      switch (status) {
        case 0:
          return "info";
          break;
        case 1:
          return "";
          break;
        case 2:
          return "warning";
          break;
        case 3:
          return "success";
          break;
        default:
          return "";
      }
    },
    rowClick(row) {
      this.workingId = row.workingId;
      this.equipmentId = row.equipmentId;
      getWorking(this.workingId).then((response) => {
        this.details = response.data;
      });
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children,
        isDisabled: node.status == 1 ? true : false,
      };
    },
    // 部门查询条件不禁用
    normalizerSearch(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      if (node.status == 1) {
        delete node.children;
      } else {
        return {
          id: node.deptId,
          label: node.deptName,
          children: node.children,
        };
      }
    },
    /** 查询工艺管理加工任务 列表 */
    getList() {
      this.loading = true;
      listWorking(this.queryParams).then((response) => {
        this.workingList = response.rows;
        this.$nextTick(function() {
        this.$refs.interfaceTable.setCurrentRow(this.workingList[0])
      })
        if (this.workingList.length > 0) {
          this.workingId = this.workingList[0].workingId;
          this.equipmentId = this.workingList[0].equipmentId;
          // 获取右侧详情
          getWorking(this.workingId).then((response) => {
            this.details = response.data;
          });
        } else {
          this.workingId = "";
          this.equipmentId = "";
          this.details = {};
        }
        this.total = response.total;
        this.loading = false;
      });
    },
    getEquipmentOptions() {
      listInfo({ status: 1 }).then((response) => {
        this.equipmentOptions = response.rows;
      });
    },
    /* 获取公司列表 */
    getDeptOptions() {
      listDept().then((response) => {
        // this.deptOptions = response.data;
        this.deptOptions = this.handleTree(response.data, "deptId");
      });
    },
    getMaterialAddMethodOptions() {
      this.getDicts("base_material_addMethod").then((response) => {
        this.materialAddMethodOptions = response.data;
      });
    },
    // 任务状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        workingId: null,
        workingCategoryId: null,
        workingNumber: null,
        time: [],
        workingName: null,
        equipmentId: null,
        deptId: null,
        description: null,
        startTime: null,
        endTime: null,
        status: -1,
        workingplanId: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        isAuto: null,
        processTypeId: null,
        technologyMaterialAddMethodId: null,
        spentTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      if (this.queryParams.time.length > 0) {
        this.queryParams.startTime = this.queryParams.time[0];
        this.queryParams.endTime = this.queryParams.time[1];
      } else {
        this.queryParams.startTime = "";
        this.queryParams.endTime = "";
      }
      this.queryParams.pageNum = 1;
      this.tableCheckbox=[]
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.time = [];
      this.resetForm("queryForm");
      this.queryParams.equipmentId = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.workingId);
      this.workingNames = selection.map((item) => item.workingName);
      this.tableCheckbox = selection;
      // 状态 打印成功和打印中 限制修改逻辑
      let len = selection.filter(
        (item) => item.status == 1 || item.status == 0
      );
      this.single = len.length > 0 || selection.length !== 1;
      this.multiple = !selection.length;
      // 强制修改按钮逻辑判断
      if (selection.length !== 1) {
        this.forceEdit = false;
        return;
      }

      this.forceEdit = len.length == 1;
    },
    // /*公司变化*/
    // selectionDeptChanged(selected) {
    //   this.queryParams.deptIds = selected.toString();
    // },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.selectItems = [];
      this.setSelectItems = [];
      this.title = "添加加工任务 ";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const workingId = row.workingId || this.ids;
      getWorking(workingId).then((response) => {
        this.open = true;
        this.$nextTick(() => {
          this.form = response.data;
          // this.selectItems = this.form.technologyWorkingParams.map((item) => {
          //   let obj = JSON.parse(item.paramJson);
          //   obj.id = item.id;
          //   return obj;
          // });
          // this.selectItems = this.form.technologyWorkingParams; //工艺预设
          this.setSelectItems = this.form.technologyWorkingMaterials; //材料
          this.title = "修改加工任务 ";
        });
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (!this.testForm()) return false;
          this.btnLoading = true;
          if (this.form.workingId != null) {
            let api=this.isForceEdit?forceEditWorking:updateWorking
            api(this.form)
              .then((response) => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
                this.isForceEdit=false
                this.btnLoading = false;
              })
              .catch(() => {
                this.btnLoading = false;
              });
          } else {
            addWorking(this.form)
              .then((response) => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
                this.btnLoading = false;
              })
              .catch(() => {
                this.btnLoading = false;
              });
          }
        }
      });
    },
    // 验证值
    testForm() {
      // let selectItems = this.$refs.parametersRef.selectItems;//取消工艺预设功能
      let setSelectItems = this.$refs.materialRef.setSelectItems;
      if (setSelectItems.length == 0) {
        this.msgError("请选择材料");
        return false;
      }

      // let selectItemsRes = selectItems.map((item) => {
      //   return {
      //     id: item.id,
      //     paramJson: JSON.stringify(item),
      //   };
      // });
      // this.form.technologyWorkingParams = selectItemsRes;
      this.form.technologyWorkingMaterials = setSelectItems;
      return true;
    },
    /** 删除按钮操作 */
    handleDelete() {
      const workingIds = this.ids;
      // 选择得数据中包含正在中任务时，提示不允许删除
      let status = 0;
      workingIds.forEach((item) => {
        let obj = this.workingList.find((li) => {
          return li.workingId == item;
        });
        if (obj.status !== -1) {
          //-1为初始化状态
          status = 1;
        }
      });
      if (status) {
        this.msgError("当前数据包含非初始化任务，请重新选择");
        return;
      }
      this.$confirm(
        '是否确认删除加工任务名称为："' + this.workingNames + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",closeOnClickModal:false,
          type: "warning",
        }
      )
        .then(function () {
          return delWorking(workingIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    handleStart(row) {
      const workingNames = this.workingNames;
      const workingIds = this.ids;
      this.$confirm('是否确认开始加工任务 "' + workingNames + '"?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",closeOnClickModal:false,
        type: "message",
      })
        .then(function () {
          return startWorking(workingIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("任务开始成功");
        });
    },
    handleSuspend(row) {
      const workingNames = this.workingNames;
      const workingIds = this.ids;
      this.$confirm('是否确认暂停加工任务 "' + workingNames + '"?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",closeOnClickModal:false,
        type: "message",
      })
        .then(function () {
          return suspendWorking(workingIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("任务暂停成功");
        });
    },
    handleContinue(row) {
      const workingNames = this.workingNames;
      const workingIds = this.ids;
      this.$confirm('是否确认继续加工任务 "' + workingNames + '"?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",closeOnClickModal:false,
        type: "message",
      })
        .then(function () {
          return continueWorking(workingIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("任务继续成功");
        });
    },
    handleFinish(row) {
      const workingNames = this.workingNames;
      const workingIds = this.ids;
      this.$confirm('是否确认完成加工任务 "' + workingNames + '"?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",closeOnClickModal:false,
        type: "message",
      })
        .then(function () {
          return finishWorking(workingIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("任务完成");
        });
    },
      /** 导出按钮操作 */
    handleExport() {
      this.btnLoading = true;
      let ids=this.tableCheckbox.map(item=>{
         return item.workingId
       })
       let query=JSON.parse(JSON.stringify(this.queryParams))
       query.workIds=ids
      this.download(
        "technology/technologyWorking/export",
        {
          ...query,
        },
        `technologyWorking.xlsx`,
        "",
        () => {
          this.btnLoading = false;
        }
      );
    },
  },
};
</script>
<style  scoped>
.item-width {
  width: 33%;
  line-height: 35px;
}
.max-text {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  word-break: break-all;
}
/* .item-width-more {
  height: 40px;
} */
</style>